package pers.ree.demo.generic;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;

/**
 * 泛型逆变的demo
 */
public class ContravariantDemo<T> {

    private List<? super T> items = new ArrayList<>();


    public ContravariantDemo(List<? super T> items) {
        this.items = items;
    }

    public void addItem(T item) {
//        items = new ArrayList<>();
        items.add(item);
    }

    public void compareNumber() {
//        Comparator<? super Number> comparator = (c1, c2) ->
//                c1.doubleValue() - c2.doubleValue();

//        Comparator<Number> comparator = (c1, c2) -> {
//            if (c1 instanceof Double || c2 instanceof Double) {
//                return ((Number) c1).floatValue() - ((Number) c2).floatValue();
//            } else {
//                // 提供一个回退逻辑，或者抛出异常
//                throw new IllegalArgumentException("Values must be of type Double");
//            }
//        };

        Comparator<? super Number> comparator1 = (c1, c2) -> {
            return Double.compare(c1.doubleValue(), c2.doubleValue());
        };


        Comparator<? super Number> comparator2 = (c1, c2) ->
                c1.intValue() - c2.intValue();
    }

    public void castType() {
        List<? super Integer> numberList = new ArrayList<Number>();
//        List<Number> numbers = numberList; // 错误，不能这样转换
        // 需要显示转换，因为这不是协变的情况
    }

    public void operateCollection() {
        List<? super String> objects = new ArrayList<Object>();
        objects.add("Hello, World!"); // 正确，String是Object的子类
    }

    public static <T> void addToList(List<? super T> list, T element) {
        list.add(element);
    }

    public static <T> List<? super T> filterList(List<T> list, Predicate<T> predicate) {
        List<? super T> result = new ArrayList<>();
        for (T item : list) {
            if (predicate.test(item)) {
                result.add(item);
            }
        }
        return result;
    }
}
